<template>
  <div class="form-cell">
    <van-field readonly clickable name="picker" :value="pickerValue" :label="label" :placeholder="placeholder || '请选择'" 
      @click="showBlank" :rules="rules" :required="required === undefined ? false : true"/>
    <van-popup v-model="showPicker" position="bottom">
      <van-datetime-picker v-model="date" type="date" @cancel="showPicker = false" @confirm="onConfirm"
        :min-date="mindate" :max-date="maxdate"/>
    </van-popup>
  </div>
</template>

<script>
export default {
  props: ["label", "value", "placeholder", "readonly", "min", "max", "required", "rules"],
  data() {
    return {
      pickerValue: "",
      date: new Date(),
      showPicker: false,
      mindate: new Date(),
      maxdate: new Date()
    };
  },
  watch: {
    value() {
      if (this.value) {
        this.date = new Date(this.value);
        this.pickerValue = this.date.format("yyyy-MM-dd");
        return;
      }
      this.pickerValue = "";
    },
  },
  methods: {
    onConfirm() {
      this.pickerValue = this.date.format("yyyy-MM-dd");
      this.$emit("input", this.pickerValue);
      this.showPicker = false;
    },
    showBlank() {
      if (this.readonly) return;
      if (this.value) {
        this.date = new Date(this.value);
      } else {
        this.date = new Date();
      }
      let now = new Date().getTime();
      let tenYear = 10 * 366 * 24 * 60 * 60 * 1000;
      if (this.min) {
        this.mindate = new Date(this.min);
      } else {
        this.mindate = new Date(now - tenYear);
      }
      if (this.max) {
        this.maxdate = new Date(this.max);
      } else {
        this.maxdate = new Date(now + tenYear);
      }
      this.$nextTick(() => {
        this.showPicker = true;
      });
    },
  },
  mounted() {
    if (this.value) {
      this.date = new Date(this.value);
      this.pickerValue = this.date.format("yyyy-MM-dd");
    }
  },
};
</script>
